/*++

    Javascript Lightweight Framework.

    Author: Nickey Woo
    Date: 2008-09-01

--*/
/*

    WooJS.js

    Core Object:
        class Browser
        {
        public:
            string  Name;
            bool    IsIE;
            bool    IsNetscape;
        };

        class Screen
        {
        public:
            int Width;
            int Height;
            int AvailableWidth;
            int AvailableHeight;
        };

        class User
        {
        public:
            Browser  Browser;
            Screen   Screen;
            
            string   GetData(string name);
            void     SetData(string name, string value);
            
            static User GetCurrentUser();
        };
 
        class Ajax
        {
        public:
            Ajax(string url, string data, void (* callback)(string response) callback)
            
            static XMLHttpRequest GetAjaxObject();
        };

        class Library
        {
        public:
            string  Url;
            void (* callback)()   OnLoadCompleted;
            
            void Load(string url); // trigger event OnLoadCompleted
        };
        
    Widget Object:
        Widget
        PopupWidget

*/

function str_replace(str, split, rep)
{
	var ret = "";

	var start = 0;
	var pos = -1;
	while((pos = str.indexOf(split, start)) != -1)
	{
		ret += str.substr(start, pos - start) + rep;
		start = pos + split.length;
	}
	ret += str.substr(start);
	return ret;
}

String.prototype.SafeReplace = function(split, rep)
{
	return str_replace(this, split, rep);
}

String.prototype.TrimLeft = function()
{
	var str = this;
	var whitespace = '\t\r\n 　';
	while(str.length > 0 && whitespace.indexOf(str.substr(0, 1)) != -1)
	{
		str = str.substr(1);
	}
	return str;
}

String.prototype.TrimRight = function()
{
	var str = this;
	var whitespace = '\t\r\n 　';
	while(str.length > 0 && whitespace.lastIndexOf(str.substr(str.length - 1, 1)) != -1)
	{
		str = str.substr(0, str.length - 1);
	}
	return str;
}

String.prototype.Trim = function()
{
	return this.TrimLeft().TrimRight();
}

// namespace WooJS
function WooJS() { }

WooJS.$ = function(id) {
    return document.getElementById(id);
}

WooJS.$Name = function(name) {
    return document.getElementsByName(name);
}

WooJS.$Tag = function(tagName) {
    return document.getElementsByTagName(tagName);
}

WooJS.$Create = function(tag) {
    return document.createElement(tag);
}

WooJS.$X = function(obj) {
    var left = 0;
    while(obj != null) {
        left += obj.offsetLeft;
        try {
            obj = obj.offsetParent;
        } catch(e) {
            return 0;
        }
    }
    return left;
}

WooJS.$Y = function(obj) {
    var top = 0;
    while(obj != null) {
        top += obj.offsetTop;
        try {
            obj = obj.offsetParent;
        } catch(e) {
            return 0;
        }
    }
    return top;
}

WooJS.$ScrollLeft = function(obj) {
    var left = 0;
    while(obj != null) {
        left += obj.scrollLeft;
        try {
            obj = obj.offsetParent;
        } catch(e) {
            return 0;
        }
    }
    return left;
}

WooJS.$ScrollTop = function(obj) {
    var top = 0;
    while(obj != null) {
        top += obj.scrollTop;
        try {
            obj = obj.offsetParent;
        } catch(e) {
            return 0;
        }
    }
    return top;
}

/*
interface:

class Browser
{
public:
    string  Name;
    bool    IsIE;
    bool    IsNetscape;
};
*/
function internal_browser() { }
internal_browser.prototype.Name = window.navigator.appName;
internal_browser.prototype.IsIE = window.navigator.appName == 'Microsoft Internet Explorer'? true : false;
internal_browser.prototype.IsNetscape = window.navigator.appName == 'Netscape'? true : false;
WooJS.Browser = internal_browser;

/*
interface:

class Screen
{
public:
    int Width;
    int Height;
    int AvailableWidth;
    int AvailableHeight;
};
*/
function internal_screen() {
    this.Width = window.screen.width;
    this.Height = window.screen.height;
    this.AvailableWidth = document.documentElement.clientWidth;
    this.AvailableHeight = document.documentElement.clientHeight;
}
internal_screen.prototype.Width = 0;
internal_screen.prototype.Height = 0;
internal_screen.prototype.AvailableWidth = 0;
internal_screen.prototype.AvailableHeight = 0;
WooJS.Screen = internal_screen;

/*
interface:

class User
{
public:
    Browser  Browser;
    Screen   Screen;
    
    string   GetData(string name);
    void     SetData(string name, string value);
    
    static User GetCurrentUser();
};
*/
function internal_user() { }
internal_user.prototype.Browser = new WooJS.Browser();
internal_user.prototype.Screen = new WooJS.Screen();
internal_user.prototype.GetData = function(sName) {
    var aCookie = document.cookie.split("; ");
    for (var i=0; i < aCookie.length; i++) {
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0]) 
            return unescape(aCrumb[1]);
    }
    return null;
}
internal_user.prototype.SetData = function(sName, sValue) {
    document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 2099 23:59:59 GMT;";
}
internal_user.GetCurrentUser = function() { return new internal_user(); }
WooJS.User = internal_user;


/*
interface:

class Ajax
{
public:
    Ajax(string url, string data, void (* callback)(string response) callback)
    
    static XMLHttpRequest GetAjaxObject();
};
*/
function internal_ajax(url, data, handler) {
	this.Url = url;
	this.Data = data;
	this.Handler = handler;
	this.errorHandler = null;
	if(arguments.length > 3&& arguments[3]) this.errorHandler = arguments[3];

    this.AjaxObj = WooJS.Ajax.GetAjaxObject();

	var CoreObj = this.AjaxObj;
	var SrcObj = this;
    this.AjaxObj.onreadystatechange = function() {
		if(CoreObj.readyState == 4 ){
			if(CoreObj.status == 200)
				if(SrcObj.Handler != null)		SrcObj.Handler(CoreObj.responseText);
			else
				if(SrcObj.errorHandler != null)		SrcObj.errorHandler();
		}
	}
}
internal_ajax.prototype.Open = function(){
	this.AjaxObj.open('GET', this.Url);
	this.AjaxObj.send();
} 
internal_ajax.prototype.Send = function() {
	this.AjaxObj.open('POST', this.Url);
	this.AjaxObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	if(arguments.length > 0)
		this.AjaxObj.send(arguments[0]);
	else
		this.AjaxObj.send(this.Data);
}
internal_ajax.GetAjaxObject = function() {
    var ajaxObj = null;
    try {
		ajaxObj = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
	        ajaxObj = new XMLHttpRequest();
        }
    }
    return ajaxObj;
}
WooJS.Ajax = internal_ajax;


/*
interface:

class Library
{
public:
    string  Url;
    void (* callback)()   OnLoadCompleted;
    
    void Load(string url); // trigger event OnLoadCompleted
};
*/
function internal_library() { }
internal_library.prototype.Url = '';
internal_library.prototype.OnLoadCompleted = null;

function ie_callback() {
    if(this.readyState == 'loaded' && this.WooObj.OnLoadCompleted != null)
        this.WooObj.OnLoadCompleted();
}

function netscape_callback() {
    if(this.WooObj.OnLoadCompleted != null)
        this.WooObj.OnLoadCompleted();
}

internal_library.prototype.Load = function(url) {
    this.Url = url;
    
    var scriptBlock = WooJS.$Create("script");
    scriptBlock.setAttribute("type", "text/javascript");
    scriptBlock.setAttribute("src", url);
    scriptBlock.WooObj = this;
    // set callback function
    var browser = new WooJS.Browser();
    if(browser.IsIE) {
        // ie callback
        scriptBlock.onreadystatechange = ie_callback;
    }
    else if(browser.IsNetscape) {
        // firefox callback
        scriptBlock.onload = netscape_callback;
    }
    else {
        // no implement
    }
    browser = null; // free
    document.getElementsByTagName('head')[0].appendChild(scriptBlock);
}
WooJS.Library = internal_library;

/*
interface:

class Page
{
public:
};
*/
function internal_globalclick_handle() {
    for(var i=0; i<WooJS.Page.GlobalClickHandle.length; ++i)
    {
        var handle = WooJS.Page.GlobalClickHandle[i];
        handle[1](handle[0]);
    }
}
function internal_globalkeydown_handle() {
    for(var i=0; i<WooJS.Page.GlobalKeyDownHandle.length; ++i)
    {
        var handle = WooJS.Page.GlobalKeyDownHandle[i];
        handle[1](handle[0]);
    }
}
function internal_globalmousemove_handle() {
    for(var i=0; i<WooJS.Page.GlobalMouseMoveHandle.length; ++i)
    {
        var handle = WooJS.Page.GlobalMouseMoveHandle[i];
        handle[1](handle[0]);
    }
}
function internal_globalmouseup_handle() {
    for(var i=0; i<WooJS.Page.GlobalMouseUpHandle.length; ++i)
    {
        var handle = WooJS.Page.GlobalMouseUpHandle[i];
        handle[1](handle[0]);
    }
}
function internal_page() {
    document.onclick = internal_globalclick_handle;
    document.onkeydown = internal_globalkeydown_handle;
    document.onmousemove = internal_globalmousemove_handle;
    document.onmouseup = internal_globalmouseup_handle;
}
internal_page.prototype.User = new WooJS.User();
internal_page.prototype.ImplPage = null;
internal_page.prototype.GlobalClickHandle = new Array();
internal_page.prototype.GlobalKeyDownHandle = new Array();
internal_page.prototype.GlobalMouseMoveHandle = new Array();
internal_page.prototype.GlobalMouseUpHandle = new Array();
internal_page.prototype.Load = function()
{
    if(WooJS.Page.ImplPage == null)
        throw '还没有注册子页实例，请调用 WooJS.Page.Register 进行注册。';
    WooJS.Page.ImplPage.Load();
}
internal_page.prototype.Register = function(pg)
{
    WooJS.Page.ImplPage = pg;
    if(this.User.Browser.IsNetscape)
    {
        document.addEventListener("DOMContentLoaded", WooJS.Page.Load, false);
    }
    else if(this.User.Browser.IsIE)
    {
        document.onreadystatechange = function() {
            if(document.readyState == 'complete')
                WooJS.Page.ImplPage.Load();
        }
    }
}
internal_page.prototype.GetRootWindow = function()
{
	var WndObj = window;
	while(WndObj != WndObj.parent)
	{
		WndObj = WndObj.parent;
	}
	return WndObj;
}
internal_page.prototype.RegisterGlobalClickHandle = function(obj, handle)
{
    var item = new Array();
    item.push(obj);
    item.push(handle);
    this.GlobalClickHandle.push(item);
}
internal_page.prototype.RegisterGlobalKeyDownHandle = function(obj, handle)
{
    var item = new Array();
    item.push(obj);
    item.push(handle);
    this.GlobalKeyDownHandle.push(item);
}
internal_page.prototype.RegisterGlobalMouseMoveHandle = function(obj, handle)
{
    var item = new Array();
    item.push(obj);
    item.push(handle);
    this.GlobalMouseMoveHandle.push(item);
}
internal_page.prototype.RegisterGlobalMouseUpHandle = function(obj, handle)
{
    var item = new Array();
    item.push(obj);
    item.push(handle);
    this.GlobalMouseUpHandle.push(item);
}
WooJS.Page = new internal_page();


/////////////////////////////////////////////////////////////////////////////
//
WooJS.UploadFileTool = function()
{
	this.DataStream = null;
	this.FilePath = null;
	this.XmlData = null;
	this.OnUploadCompleted = null;
}

WooJS.UploadFileTool.prototype.UploadCallback = function(msg)
{
	if(this.SourceObj.OnUploadCompleted)
		this.SourceObj.OnUploadCompleted(msg);
}

WooJS.UploadFileTool.prototype.Upload = function(requestUrl, path, postData)
{
	this.FilePath = path;
	if(this.FilePath == "")
		return;

	this.GetBinaryStream();
	this.BuildXmlData();

	var SendData = "";
	if(postData == "")
	{
		SendData = "xml="+escape(this.XmlData.xml);
	}
	else
	{
		SendData = postData + "&xml="+escape(this.XmlData.xml);
	}
	var sender = new WooJS.Ajax(requestUrl, SendData, this.UploadCallback);
	sender.SourceObj = this;
	sender.Send();
}

WooJS.UploadFileTool.prototype.GetBinaryStream = function()
{
	var stream = new ActiveXObject("ADODB.Stream");
	stream.Type = 1;
	stream.Open();
	stream.LoadFromFile(this.FilePath);
	if(stream.Size > 1048576)
	{
		stream.Close();
		throw "上传文件大于1MB，禁止上传。";
	}
	this.DataStream = stream.Read();
	stream.Close();
}

WooJS.UploadFileTool.prototype.BuildXmlData = function()
{
	var fileName = this.FilePath.substr(this.FilePath.lastIndexOf("\\") + 1);
	this.XmlData = new ActiveXObject("MSXML2.DOMDocument");
	this.XmlData.loadXML("<?xml version=\"1.0\"?><File/>");
	this.XmlData.documentElement.setAttribute("xmlns:dt", "urn:schemas-microsoft-com:datatypes");
	var nameNode = this.XmlData.createElement("Name");
	if(/^[a-zA-Z0-9\.]*$/gi.test(fileName))
		nameNode.text = fileName;
	else
	{
		var posExt = fileName.lastIndexOf('.');
		if(posExt != -1)
			nameNode.text = Math.random() + fileName.substr(posExt);
		else
			nameNode.text = Math.random() + ".jpg";
	}
	this.XmlData.documentElement.appendChild(nameNode);
	var dataNode = this.XmlData.createElement("Data");
	dataNode.dataType = "bin.hex";
	dataNode.nodeTypedValue = this.DataStream;
	this.XmlData.documentElement.appendChild(dataNode);
}

